package com.estar.app.business.mobileLogin.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.log4j.Logger;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.tag.vo.datatable.SortDirection;
import org.jeecgframework.web.system.pojo.base.TSTimeTaskEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.estar.app.business.common.service.AppService;
import com.estar.app.business.mobileLogin.entity.ReturnSMSEntity;
import com.estar.app.business.mobileLogin.entity.ReturnSMSReplyEntity;
import com.estar.platform.caseInfo.entity.TmblSendSMS;
import com.hp.hpl.sparta.xpath.ThisNodeTest;
import com.thoughtworks.xstream.XStream;

/** 
 * 基于xml的定时器 
 * @author hj 
 */  

@Component("updateSatisfaction")
@Scope("prototype")
public class UpdateSatisfaction extends BaseController{  
	
	public final static String returnSmsUrl = "https://smsapi.ums86.com:9600/sms/Api/replyConfirm.do";
/*	public final static String SpCode2="238622";//企业编号
	public final static String LoginName2="admin0";//	用户名称
	public final static String Password2="GAii123456!"	;//用户密码
*/	
	public final static String SpCode2="242692";//企业编号
	public final static String LoginName2="admin3";//	用户名称
	public final static String Password2="gaii38788102"	;//用户密码
	@Autowired
	AppService appService;
	private static final Logger logger = Logger.getLogger(UpdateSatisfaction.class);
    public void updateByThreeDay(){  
    	
    	//获取运行权限
    	CriteriaQuery cq1 = new CriteriaQuery(TSTimeTaskEntity.class);
    	cq1.eq("taskId", "updateSatisfaction.do?updateByThreeDay");
    	cq1.add();
    	List<TSTimeTaskEntity> timeTaskList = appService.getListByCriteriaQuery(cq1, false);
    	TSTimeTaskEntity timeTask = null;
    	if(0 != timeTaskList.size()){
    		timeTask = timeTaskList.get(0);
    		if("1".equals(timeTask.getIsEffect()) && "1".equals(timeTask.getIsStart())){
        		
        		//获取当前时刻三天前的时间
        		Date threeDaysAgo = getThreeDaysAgo(new Date()) ;
        	    
        	    //查找三天前的数据
            	CriteriaQuery cq = new CriteriaQuery(TmblSendSMS.class);
            	cq.isNull("satisfaction");
            	cq.add(Restrictions.le("sendTime", threeDaysAgo));
            	cq.add();
            	List<TmblSendSMS> sendSMSList = appService.getListByCriteriaQuery(cq, false);
            	
            	//将满意度为空的修改为非常满意
            	for(TmblSendSMS ts: sendSMSList){
            		if(null == ts.satisfaction || ts.satisfaction.isEmpty()){
            			System.out.println(ts.reportNo);
            			ts.setSatisfaction("2");
            			ts.setTimeOut("y");
            			appService.saveOrUpdate(ts);
            		}
            	}
        	}
    	}
    }  
    
    
    //判断短信内容
 	public String checkSatisfaction(String str) {
 		if ("0".equals(str) || "1".equals(str) || "2".equals(str)) {
 			return str;
 		}
 		return "1";
 	}
    
    public void updateBySms() throws Exception{
    	
    	//获取运行权限
    	CriteriaQuery cq1 = new CriteriaQuery(TSTimeTaskEntity.class);
    	cq1.eq("taskId", "updateSatisfaction.do?updateBySms");
    	cq1.add();
    	List<TSTimeTaskEntity> timeTaskList = appService.getListByCriteriaQuery(cq1, false);
    	
    	TSTimeTaskEntity timeTask = null;
    	if(0 != timeTaskList.size()){
    		timeTask = timeTaskList.get(0);
    		if("1".equals(timeTask.getIsEffect()) && "1".equals(timeTask.getIsStart())){
    			
    			
        		//String 转 Date 
            	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            	//回复时间
            	Date replyTime = null;
            	
        	    
            	//搜索这个小时内的回复短信
        	    //1.获取2小时前的时刻
        	    Date twoHoursAgo = getTwoHoursAgo(new Date()) ;
        	    
            	String startTime = sdf.format(twoHoursAgo);
            	//System.out.println(startTime);
            	//2.获取当前时间
            	String endTime = sdf.format(new Date());
            	//System.out.println(endTime);
            	
            	//旧模板
            	/*List<ReturnSMSReplyEntity> result = new ArrayList<ReturnSMSReplyEntity>();
            	for(Integer pageNum = 1; pageNum < 6 ; pageNum++){
            		List<ReturnSMSReplyEntity> testResult = RespCheckUtil.returnSMS(startTime, endTime, pageNum);
            		
            		if(null != testResult &&!"".equals(testResult)){
            			result.addAll(testResult);
            		}
            	}
            	dealWithResult(result, replyTime, sdf);*/
    			
    			//联通模板
            	try{
            	JSONArray result=RespCheckUtil.returnSMS();
            	logger.info("短信返回内容："+result.toString());
            	if(result.size()>0){
            		dealWithResult(result, replyTime, sdf);
            	}
            	}catch(Exception e){
            		logger.error("系统异常：",e);
            		e.printStackTrace();
            	}
        	}
    	}
    }
    
    //旧模板
   /* public void dealWithResult(List<ReturnSMSReplyEntity> result, Date replyTime, SimpleDateFormat sdf) throws Exception{
    	int smsNum = 0;
    	if(null != result && !"".equals(result)){
    		for(ReturnSMSReplyEntity returnSMSReply : result){
    			
    			//手机号数量
    			smsNum++;
    			System.out.println(smsNum);
 			
        		if(null != returnSMSReply && !"".equals(returnSMSReply)){		
        			//根据手机号查询
        			CriteriaQuery cq = new CriteriaQuery(TmblSendSMS.class);
            		cq.eq("visitPhone", returnSMSReply.getMobile());
            		cq.addOrder("sendTime", SortDirection.asc);
            		cq.add();
            		
                	List<TmblSendSMS> sendSMSList = appService.getListByCriteriaQuery(cq, false);
                	try {
                		if(0 != sendSMSList.size()){
                    		//若满意度为空，则修改满意度并保存
                    		for(TmblSendSMS sendSMS:sendSMSList){
                    			if(null == sendSMS.getSatisfaction() || "".equals(sendSMS.getSatisfaction())){
                            		
                            		//若回复时间超过发送时间三天，则回复无效
    								replyTime = sdf.parse(returnSMSReply.getReply_time());
    								long overTime = getThreeDaysAfter(sendSMS.getSendTime()).getTime();
                            		if(replyTime.getTime()<overTime){
                            			
                            			//满足以上条件，则修改满意度
                            			//1.判断短信内容
                            			sendSMS.setSatisfaction(checkSatisfaction(returnSMSReply.getText()));
                                		appService.updateEntitie(sendSMS);
                            		}
                            	}
                    		}
                    	}
                	}catch (ParseException e) {
						throw e;
					}
                	
        		}
        	}
    	}
    }*/
    //联通模板
    public void dealWithResult(JSONArray result, Date replyTime, SimpleDateFormat sdf) throws Exception{
    	int smsNum = 1;
    	try {
    		for(int i=0;i<result.size();i++){
    			
    			//手机号数量
    			smsNum++;
    			JSONObject o = result.getJSONObject(i);
        			//根据手机号查询
        			CriteriaQuery cq = new CriteriaQuery(TmblSendSMS.class);
            		cq.eq("visitPhone", o.getString("mdn"));
            		cq.isNull("satisfaction");
            		cq.addOrder("sendTime", SortDirection.asc);
            		cq.add();
            		
                	List<TmblSendSMS> sendSMSList = appService.getListByCriteriaQuery(cq, false);
                	
                		if(0 < sendSMSList.size() && sendSMSList!=null){
                    		//若满意度为空，则修改满意度并保存
                    		for(TmblSendSMS sendSMS:sendSMSList){
                    			if(null == sendSMS.getSatisfaction() || "".equals(sendSMS.getSatisfaction())){
                            		
                            		//若回复时间超过发送时间三天，则回复无效
    								replyTime = sdf.parse(o.getString("reply_time"));
    								long overTime = getThreeDaysAfter(sendSMS.getSendTime()).getTime();
                            		if(replyTime.getTime()<overTime){
                            			
                            			//满足以上条件，则修改满意度
                            			//1.判断短信内容
                            			sendSMS.setSatisfaction(checkSatisfaction(o.getString("content")));
                            			sendSMS.setTimeOut("");
                                		appService.updateEntitie(sendSMS);
                            		}
                            	}
                    		}
                    	}
                	
                	if(smsNum>=result.size()){
                		String id =o.getString("id");
                		String reulst=replyConfirm(id);
                		logger.info("短信回复内容确认："+reulst);
                	}
        		}
    		
    	}catch (Exception e) {
    		logger.error("更新短信系统异常：",e);
			throw e;
		}
        	
    }
    
    public Date getThreeDaysAfter(Date date){
    	//获取当前时刻三天后的时间
    	Calendar threeDaysAfter = Calendar.getInstance();  
    	threeDaysAfter.setTime(date);  
	    threeDaysAfter.set(Calendar.DATE, threeDaysAfter.get(Calendar.DATE) + 3);
	    return threeDaysAfter.getTime();
    }
    public Date getThreeDaysAgo(Date date){
    	//获取当前时刻三天后的时间
    	Calendar threeDaysAgo = Calendar.getInstance();  
    	threeDaysAgo.setTime(date);  
	    threeDaysAgo.set(Calendar.DATE, threeDaysAgo.get(Calendar.DATE) - 3);
	    return threeDaysAgo.getTime();
    }
    public Date getTwoHoursAgo(Date date){
    	Calendar twoHoursAgo = Calendar.getInstance(); 
    	twoHoursAgo.setTime(date);
    	twoHoursAgo.set(Calendar.HOUR_OF_DAY, twoHoursAgo.get(Calendar.HOUR_OF_DAY) - 2);
    	return twoHoursAgo.getTime();
    }
    
    public static String replyConfirm(String id) throws Exception{
     	HttpClient httpclient = new HttpClient();
		PostMethod post = new PostMethod(returnSmsUrl);
		post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"gbk");
		post.addParameter("SpCode", SpCode2);
		post.addParameter("LoginName", LoginName2);
		post.addParameter("Password", Password2);
		post.addParameter("id", id);
		httpclient.executeMethod(post);
		String info = new String(post.getResponseBody(),"gbk");
		httpclient.getHttpConnectionManager().closeIdleConnections(0);
		return info;
		
     
 }
//    public static void main(String[] args) throws Exception {
//    	updateBySms();
//	}
}